package com.UKIT.airtickets.Activities.fragments

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import androidx.room.Room
import com.UKIT.airtickets.Activities.AuthorizationActivity
import com.UKIT.airtickets.Activities.SettingsActivity
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.DB.UserDao
import com.UKIT.airtickets.R
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.databinding.FragmentAccountBinding
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.coroutines.*
import java.io.File
import java.io.FileOutputStream

class AccountFragment : Fragment() {

    private lateinit var binding: FragmentAccountBinding
    private val DEFAULT_AVATAR_RESOURCE_ID = R.drawable.profile


    lateinit var userDao: UserDao
    lateinit var db: AppDatabase
    private var userId: Long = -1

    private lateinit var settingsBtn: ImageView
    private lateinit var profilePhotoImageView: CircleImageView
    private lateinit var userNameTittle: TextView
    private lateinit var userSecondNameTittle: TextView
    private lateinit var editUserName: EditText
    private lateinit var editUserSecondName: EditText
    private lateinit var saveChangesBtn: Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        db = Room.databaseBuilder(requireContext(), AppDatabase::class.java, "airtickets.db")
            .fallbackToDestructiveMigration()
            .build()

        binding = FragmentAccountBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        userId = SettingsApp.userId
        binding.settingsButton.setOnClickListener {
            val intent = Intent(requireContext(), SettingsActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }

        with(binding) {
            profilePhotoImageView = userAvatar
            userNameTittle = userNameTitle
            userSecondNameTittle = userSecondNameTitle
            this@AccountFragment.editUserName = editUserName
            this@AccountFragment.editUserSecondName = editUserSecondName
            saveChangesBtn = saveChangesButton
        }

        setupChangePhotoButton()
        setupSaveChangesButton()
        loadUser()
        setupLogoutButton()
    }

    fun setupChangePhotoButton() {
        binding.userAvatar.setOnClickListener {
            pickImageLauncher.launch(Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI))
        }
    }

    fun setupSaveChangesButton() {
        binding.saveChangesButton.setOnClickListener {
            saveChangesAndUpdateUI()
        }
    }

    fun setupLogoutButton() {
        binding.logoutButton.setOnClickListener {
            logout()
        }
    }

    fun logout() {
        clearCache()
        redirectToAuthorizationActivity()
        showToast("Выход успешно осуществлён")
    }

    private fun clearCache() {
        val sharedPreferences = requireContext().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        sharedPreferences.edit {
            putInt("user_id", 0)
        }
    }

    private fun redirectToAuthorizationActivity() {
        val intent = Intent(requireContext(), AuthorizationActivity::class.java)
        startActivity(intent)
        requireActivity().finish()
    }

    private fun showToast(message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }


    fun saveChangesAndUpdateUI() {
        val newName = editUserName.text.toString()
        val newSecondName = editUserSecondName.text.toString()

        GlobalScope.launch(Dispatchers.IO) {
            val rowsAffected = db.userDao().updateUserDetails(userId, newName, newSecondName)
            val message = if (rowsAffected > 0) {
                "Успешно"
            } else {
                "Произошла непредвиденная ошибка"
            }
            launch(Dispatchers.Main) {
                Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
                loadUser()
            }
        }
    }

    private fun loadUser() {
        GlobalScope.launch(Dispatchers.IO) {
            val user = db.userDao().getUserById(userId)
            launch(Dispatchers.Main) {
                user?.let {
                    userNameTittle.text = if(it.firstName == "") "Имя: " else it.firstName
                    userSecondNameTittle.text = if(it.lastName == "") "Фамилия: " else it.lastName
                    if(it.avatar == ""){
                        profilePhotoImageView.setImageResource(DEFAULT_AVATAR_RESOURCE_ID)
                    }
                    else{
                        profilePhotoImageView.setImageURI(Uri.parse(it.avatar))
                    }
                }
            }
        }
    }

    fun saveImageToCache(context: Context, bitmap: Bitmap): Uri {
        val cacheDir = context.cacheDir
        val file = File(cacheDir, "profile_image.jpg")
        FileOutputStream(file).use { outputStream ->
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
        }
        return Uri.fromFile(file)
    }

    val pickImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val selectedImageUri = result.data?.data
            val bitmap: Bitmap = selectedImageUri?.let { uriToBitmap(it) } ?: return@registerForActivityResult
            val cachedImageUri = saveImageToCache(requireContext(), bitmap)
            profilePhotoImageView.setImageURI(cachedImageUri)

            GlobalScope.launch(Dispatchers.IO) {
                val imagePath = cachedImageUri.toString()
                val rowsAffected = db.userDao().updateUserAvatar(userId, imagePath)
                launch(Dispatchers.Main) {
                    if (rowsAffected <= 0) {
                        Toast.makeText(requireContext(), "Ошибка загрузки фото", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    fun uriToBitmap(uri: Uri): Bitmap {
        return MediaStore.Images.Media.getBitmap(requireContext().contentResolver, uri)
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }
}
